package org.browntooth.app.bluetooth.messaging;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.browntooth.app.bluetooth.BluetoothDeviceConnection;

import android.util.Log;

public class SyncBluetoothMessagingDeviceConnection {
	private final BluetoothDeviceConnection connection;
	private final InputStream inputStream;
	private final OutputStream outputStream;

	public SyncBluetoothMessagingDeviceConnection(
			BluetoothDeviceConnection connection) throws IOException {
		this.connection = connection;
		inputStream = this.connection.getInputStream();
		outputStream = this.connection.getOutputStream();
	}

	public void send(BluetoothMessage message) throws IOException {
		byte[] data = message.getData();
		byte[] lengthData = BluetoothMessagingUtils
				.buildLengthField(data.length);

		Log.d("Browntooth", "SENDING: " + data.length);

		outputStream.write(lengthData);
		outputStream.write(data);

	}

	public BluetoothMessage waitForMessage() throws IOException {
		byte[] lengthData = new byte[4];
		inputStream.read(lengthData);
		int length = BluetoothMessagingUtils.parseLength(lengthData);

		Log.d("Browntooth", "RECIEVING: " + length);

		byte[] data = new byte[length];
		inputStream.read(data);
		return new BluetoothMessage(data);
	}
}
